# -*- coding: utf-8 -*-
import time
import json
import hashlib
import datetime

import requests
from django.shortcuts import render
from django.http import JsonResponse

requests.packages.urllib3.disable_warnings()


def index(request):
    return render(request, 'index.html')  # 第一个参数必须是request


result = []


def writedata(fn):
    def fun(data):
        c = fn(data)
        res = json.loads(c.content.decode('utf-8'))
        if res.get('click') == 1:
            result.insert(0, {
                'date': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                'lablename': data.POST.get('lablename'),
                'region': data.POST.get('region'),
                'name': data.POST.get('name'),
                'Authorization': data.POST.get('Authorization', "-"),
                'canshu': json.loads(data.POST.get('canshu')),
                'sum': data.POST.get('sum'),
                'res': json.loads(c.content.decode('utf-8')),
            })
        return c

    return fun


def getlist(request):
    res = {'click': 1, "messages": "发送成功", 'data': result}
    return JsonResponse(res)


@writedata
def xielou(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, Authorization, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        json1 = [{
            "riskId": sign,
            "classify": data1['classify'],
            "issueName": data1['issueName'],
            "riskLevel": data1['riskLevel'],
            "lastUpdateTime": starttime,
            "dbType": data1['dbType'],
            "issueIP": data1['issueIP'],
            "issuePort": data1['issuePort'],
            "riskHistory": data1['riskHistory'],
            "evidenceInfo": data1['evidenceInfo'],
            "issueSolution": data1['issueSolution'],
            "lawInfo": data1['lawInfo'],
            "discoverFactory": data1['discoverFactory'],
            "eventFrom": data1['eventFrom'],
            "probeIp": data1['probeIp'],
            "operationMark": data1['operationMark'],
            "dataFrom": data1['dataFrom']
        }]
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Connection': 'close',
        'Authorization': Authorization
    }
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})


@writedata
def loudong(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, Authorization, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        json1 = [{
            "riskId": sign,
            "classify": data1['classify'],
            "issueName": data1['issueName'],
            "riskLevel": data1['riskLevel'],
            "dataFrom": data1['dataFrom'],
            "lastUpdateTime": starttime,
            "dbType": data1['dbType'],
            "issueIP": data1['issueIP'],
            "issuePort": data1['issuePort'],
            "riskHistory": data1['riskHistory'],
            "issueSolution": data1['issueSolution'],
            "lawInfo": data1['lawInfo'],
            "discoverFactory": data1['discoverFactory'],
            "eventFrom": data1['eventFrom'],
            "probeIp": data1['probeIp'],
            "operationMark": data1['operationMark'],
            "affectLevel": data1['affectLevel'],
            "issuePriorityModel": data1['issuePriorityModel'],
            "issueAc": data1['issueAc'],
            "issueResult": data1['issueResult'],
            "@timestamp": data1['@timestamp'],
            "issueDescription": data1['issueDescription'],
            "issueLevel": data1['issueLevel'],
            "cve": data1['cve'],
            "cnvd": data1['cnvd'],
            "cvss": data1['cvss'],
            "issuePoc": data1['issuePoc'],
        }]
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Connection': 'close',
        'Authorization': Authorization
    }
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})


@writedata
def wangzhan(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, Authorization, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        json1 = [{
            "riskId": sign,
            "classify": data1['classify'],
            "issueName": data1['issueName'],
            "riskLevel": data1['riskLevel'],
            "dataFrom": data1['dataFrom'],
            "lastUpdateTime": starttime,
            "issueIP": data1['issueIP'],
            "issuePort": data1['issuePort'],
            "riskHistory": data1['riskHistory'],
            "issueSolution": data1['issueSolution'],
            "lawInfo": data1['lawInfo'],
            "discoverFactory": data1['discoverFactory'],
            "eventFrom": data1['eventFrom'],
            "probeIp": data1['probeIp'],
            "operationMark": data1['operationMark'],
            "riskDetail": data1['riskDetail'],
            "dataSample": data1['dataSample'],
            "issueUrl": data1['issueUrl'],
            "sensitiveInformation": data1['sensitiveInformation'],
            "checkMethod": data1['checkMethod']
        }]
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Connection': 'close',
        'Authorization': Authorization
    }
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})


@writedata
def send_dataapi(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        nowtime1 = int(time.time() * 1000)
        json1 = {
            "dataValues": [{
                "incidentID": sign,
                "eventFrom": data1['eventFrom'],
                "discoverFactory": data1['discoverFactory'],
                "sourceIncidentID": sign,
                "eventsType": data1['eventsType'],
                "eventsThreatSeverity": data1['eventsThreatSeverity'],
                "startTime": starttime,
                "attacker": data1['attacker'],
                "attackPort": data1['attackPort'],
                "victim": data1['victim'],
                "destPort": data1['destPort'],
                "transportProtocol": data1['transportProtocol'],
                "appProtocol": data1['appProtocol'],
                "ruleId": data1['ruleId'],
                "requestBody": data1['requestBody'],
                "requestDomain": data1['requestDomain'],
                "requestMethod": data1['requestMethod'],
                "clientInfo": data1['clientInfo'],
                "appPotocolVersion": data1['appPotocolVersion'],
                "requestUrl": data1['requestUrl'],
                "requestUrlQuery": data1['requestUrlQuery'],
                "httpQuote": data1['httpQuote'],
                "responseCode": data1['responseCode'],
                "responseMsg": data1['responseMsg'],
                "sensitiveDataCount": data1['sensitiveDataCount'],
                "evidence": data1['evidence'],
                "probeIp": data1['probeIp'],
                "dataFrom": data1['dataFrom'],
                "sensitiveType": data1['sensitiveType']
            }],
            "user": "admin",
            "timestamp": nowtime1,
            "sign": sign
        }
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {'Content-Type': 'application/json;charset=UTF-8'}
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})


@writedata
def send_dataaccont(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        nowtime1 = int(time.time() * 1000)
        json1 = {
            "dataValues": [{
                "incidentID": sign,
                "eventFrom": data1['eventFrom'],
                "discoverFactory": data1['discoverFactory'],
                "sourceIncidentID": sign,
                "eventsType": data1['eventsType'],
                "eventsThreatSeverity": data1['eventsThreatSeverity'],
                "startTime": starttime,
                "attacker": data1['attacker'],
                "attackPort": data1['attackPort'],
                "victim": data1['victim'],
                "destPort": data1['destPort'],
                "transportProtocol": data1['transportProtocol'],
                "appProtocol": data1['appProtocol'],
                "ruleId": data1['ruleId'],
                "requestBody": data1['requestBody'],
                "requestDomain": data1['requestDomain'],
                "requestMethod": data1['requestMethod'],
                "clientInfo": data1['clientInfo'],
                "appPotocolVersion": data1['appPotocolVersion'],
                "requestUrl": data1['requestUrl'],
                "requestUrlQuery": data1['requestUrlQuery'],
                "httpQuote": data1['httpQuote'],
                "responseCode": data1['responseCode'],
                "responseMsg": data1['responseMsg'],
                "sensitiveDataCount": data1['sensitiveDataCount'],
                "evidence": data1['evidence'],
                "probeIp": data1['probeIp'],
                "dataFrom": data1['dataFrom'],
                "sensitiveType": data1['sensitiveType'],
                "sourceUsername": data1['sourceUsername'],
            }],
            "user": "admin",
            "timestamp": nowtime1,
            "sign": sign
        }
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {'Content-Type': 'application/json;charset=UTF-8'}
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})


@writedata
def send_dataclient(request):
    url = request.POST.get('name')
    sum = request.POST.get('sum')
    Authorization = request.POST.get('Authorization')
    canshu = request.POST.get('canshu')
    if not all([url, sum, canshu]):
        return JsonResponse(
            {'click': 0, "messages": "缺少参数", 'data': {'url': url, 'sum': sum, 'Authorization': Authorization}})
    try:
        sign = hashlib.md5((str(int(time.time() * 1000)) + 'admin' + 'aavqhvv6lt').encode('utf-8')).hexdigest()
        data1 = json.loads(canshu)
        starttime = datetime.datetime.now().strftime(('%Y-%m-%d %H:%M:%S'))
        nowtime1 = int(time.time() * 1000)
        json1 = {
            "dataValues": [{
                "incidentID": sign,
                "eventFrom": data1['eventFrom'],
                "discoverFactory": data1['discoverFactory'],
                "sourceIncidentID": sign,
                "eventsType": data1['eventsType'],
                "eventsThreatSeverity": data1['eventsThreatSeverity'],
                "startTime": starttime,
                "attacker": data1['attacker'],
                "attackPort": data1['attackPort'],
                "victim": data1['victim'],
                "destPort": data1['destPort'],
                "transportProtocol": data1['transportProtocol'],
                "appProtocol": data1['appProtocol'],
                "ruleId": data1['ruleId'],
                "requestBody": data1['requestBody'],
                "requestDomain": data1['requestDomain'],
                "requestMethod": data1['requestMethod'],
                "clientInfo": data1['clientInfo'],
                "appPotocolVersion": data1['appPotocolVersion'],
                "requestUrl": data1['requestUrl'],
                "requestUrlQuery": data1['requestUrlQuery'],
                "httpQuote": data1['httpQuote'],
                "responseCode": data1['responseCode'],
                "responseMsg": data1['responseMsg'],
                "sensitiveDataCount": data1['sensitiveDataCount'],
                "evidence": data1['evidence'],
                "probeIp": data1['probeIp'],
                "dataFrom": data1['dataFrom'],
                "sensitiveType": data1['sensitiveType'],
                "sourceUsername": data1['sourceUsername'],
            }],
            "user": "admin",
            "timestamp": nowtime1,
            "sign": sign
        }
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'处理请求参数错误:{e}', 'data': {'canshu': canshu}})
    try:
        sum = int(sum)
    except Exception as e:
        return JsonResponse({'click': 0, "messages": f'次数输入数字:{e}', 'data': {'canshu': canshu}})
    header = {'Content-Type': 'application/json;charset=UTF-8'}
    n = 0
    succ = []
    fal = []
    while n < sum:
        try:
            # url = "https://192.168.50.18:4000/"
            res = requests.post(url=url, json=json1, headers=header, verify=False)
            assert res.json().get('success') == True
            succ.append(f"{res.json().get('success')}")
        except Exception as e:
            fal.append(str(e))
        n += 1
    return JsonResponse({
        'click': 1, "messages": f'发送成功:{len(succ)}次，失败了{len(fal)}次！', 'data': {'succ': succ, 'fal': fal}})
